//
//  CompanyViewController.m
//  Btpin
//
//  Created by Vic on 2019/3/10.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "CompanyJobViewController.h"
#import "CompanyOfJobStatusCell.h"
#import "LYTitleView.h"
#import "CompanyJobModel.h"
#import "CompanyJobPostedViewController.h"
#import "CompanyJobDetailViewController.h"
#import "CompanyInfoViewController.h"

@interface CompanyJobViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    NSMutableArray *allDataArray;
    NSMutableArray *openDataArray;
    NSMutableArray *inreviewDataArray;
    NSMutableArray *rejectedDataArray;
    NSMutableArray *hiddenDataArray;
    
    NSInteger currentPageAll;
    NSInteger currentPageOpen;
    NSInteger currentPageInreview;
    NSInteger currentPageRejected;
    NSInteger currentPageHidden;
    
    LYTitleView *titleView;
    UIView *baseBgView;
}
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) UITableView *jobTableView;
@end

@implementation CompanyJobViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.selectIndex = 0;
    allDataArray = [NSMutableArray arrayWithCapacity:0];
    openDataArray = [NSMutableArray arrayWithCapacity:0];
    inreviewDataArray = [NSMutableArray arrayWithCapacity:0];
    rejectedDataArray = [NSMutableArray arrayWithCapacity:0];
    hiddenDataArray = [NSMutableArray arrayWithCapacity:0];
    currentPageAll = 1;
    currentPageOpen = 1;
    currentPageInreview = 1;
    currentPageRejected = 1;
    currentPageHidden = 1;
    
    if ([DataToolsControl sharedManager].companyBaseInfoModel && [DataToolsControl sharedManager].companyBaseInfoModel.userinfo.name.length) {
        if ((([DataToolsControl sharedManager].companyBaseInfoModel && [DataToolsControl sharedManager].companyBaseInfoModel.audit.length) && ([[DataToolsControl sharedManager].companyBaseInfoModel.audit integerValue]==1))) {
            [self initUI];
            [self loadData];
        } else {
            [self baseInitUI];
        }
    } else {
        [self loadDataBaseData];
    }
    
//    [self initUI];
//    [self loadData];
}
- (void)loadDataAndToTop {
    if (self.jobTableView) {
        switch (self.selectIndex) {
            case 0: { // 全部
                currentPageAll = 1;
            } break;
            case 1: { // 开放中
                currentPageOpen = 1;
            } break;
            case 2: { // 审核中
                currentPageInreview = 1;
            } break;
            case 3: { // 审核失败
                currentPageRejected = 1;
            } break;
            case 4: { // 已隐藏
                currentPageHidden = 1;
            } break;
            default:
                break;
        }
        
        if (self.jobTableView.contentOffset.y !=0) {
            [self.jobTableView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
        [self loadData];
    } else {
        [self loadDataBaseData];
    }
}
- (void)loadDataBaseData {
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [BaseNetManager requestWithMethod:POST path:Company_GetBaseInfo_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            [DataToolsControl dataAnalysisUserBaseInfoForCompany:responseObject];
            [DataToolsControl sharedManager].companyBaseInfoModel = [[CompanyBaseInfoModel alloc] init];
            [[DataToolsControl sharedManager].companyBaseInfoModel setValuesForKeysWithDictionary:responseObject[@"data"]];
            if ((([DataToolsControl sharedManager].companyBaseInfoModel && [DataToolsControl sharedManager].companyBaseInfoModel.audit.length) && ([[DataToolsControl sharedManager].companyBaseInfoModel.audit integerValue]==1))) {
                [self initUI];
                [self loadData];
            } else {
                [self baseInitUI];
            }
            SVPHUDDismiss;
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)baseInitUI {
    if (!baseBgView) {
        baseBgView = [UIToolsControl initViewWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) backgroundColor:COLOR_OF_WHITE];
        [self.view addSubview:baseBgView];
        
        UILabel *topLbl = [UIToolsControl initLabelWithFrame:CGRectMake(0, 100*Scale, WIDTH, 40*Scale) text:@"您未完成企业认证，不能发布职位" textColor:THEMECOLOR_OF_TEXT_333333 font:Font_21];
        topLbl.textAlignment = NSTextAlignmentCenter;
        [baseBgView addSubview:topLbl];
        
        UIImageView *imgView = [UIToolsControl initImageViewWithFrame:CGRectMake(110*Scale, EndY(topLbl)+40*Scale, WIDTH-220*Scale, 120*Scale) imageName:@"qiyerenzheng-panduan"];
        [baseBgView addSubview:imgView];
        
        UILabel *bottomLbl = [UIToolsControl initLabelWithFrame:CGRectMake(0, EndY(imgView), WIDTH, 45*Scale) text:@"企业公司营业执照" textColor:THEMECOLOR_OF_TEXT_9a9a9a font:Font_13];
        bottomLbl.textAlignment = NSTextAlignmentCenter;
        [baseBgView addSubview:bottomLbl];
        
        UIButton *gotoBtn = [UIToolsControl initButtonWithFrame:CGRectMake(40*Scale, EndY(bottomLbl)+30*Scale, WIDTH-80*Scale, 50*Scale) imageName:nil target:self action:@selector(gotoBtnTap) title:@"立刻去完善认证" titleColor:COLOR_OF_WHITE];
        gotoBtn.layer.cornerRadius = 25*Scale;
        gotoBtn.layer.masksToBounds = YES;
        gotoBtn.backgroundColor = THEMECOLOR_OF_ORANGE;
        [baseBgView addSubview:gotoBtn];
    }
}
- (void)gotoBtnTap {
    if (Signin) {
        UITabBarController *tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        tabBarController.selectedIndex = tabBarController.viewControllers.count-1;
        RootNavigationController *navigationController = (RootNavigationController *)tabBarController.selectedViewController;
        CompanyInfoViewController *CIVC = [[CompanyInfoViewController alloc] init];
        CIVC.hidesBottomBarWhenPushed = YES;
        [navigationController pushViewController:CIVC animated:NO];
    } else {
        [UIToolsControl presentSignin:self callBack:^(BOOL signinFlag) {
            
        }];
    }
}
- (void)loadData {
    self.noDataView.hidden = YES;
    SVPHUDShow;
    NSString *status = @"0";
    NSString *page = @"1";
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    switch (self.selectIndex) {
        case 0: { // 全部
            status = @"0";
            page = [NSString stringWithFormat:@"%ld", (long)currentPageAll];
        } break;
        case 1: { // 开放中
            status = @"1";
            page = [NSString stringWithFormat:@"%ld", (long)currentPageOpen];
        } break;
        case 2: { // 审核中
            status = @"2";
            page = [NSString stringWithFormat:@"%ld", (long)currentPageInreview];
        } break;
        case 3: { // 审核失败
            status = @"3";
            page = [NSString stringWithFormat:@"%ld", (long)currentPageRejected];
        } break;
        case 4: { // 已隐藏
            status = @"4";
            page = [NSString stringWithFormat:@"%ld", (long)currentPageHidden];
        } break;
        default:
            break;
    }
    [dic setObject:status forKey:@"status"];
    [dic setObject:page forKey:@"page"];
    [dic setObject:PageSize forKey:@"number"];
    
    [BaseNetManager requestWithMethod:POST path:Company_GetJob_Lists_URL params:dic successBlock:^(NSDictionary * _Nonnull responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            id data = responseObject[@"data"];
            if ([data isKindOfClass:[NSArray class]]) {
                switch (self.selectIndex) {
                    case 0: { // 全部
                        if (self->currentPageAll == 1) {
                            if (self->allDataArray.count) {
                                [self->allDataArray removeAllObjects];
                            }
                        };
                    } break;
                    case 1: { // 开放中
                        if (self->currentPageOpen == 1) {
                            if (self->openDataArray.count) {
                                [self->openDataArray removeAllObjects];
                            }
                        }
                    } break;
                    case 2: { // 审核中
                        if (self->currentPageInreview == 1) {
                            if (self->inreviewDataArray.count) {
                                [self->inreviewDataArray removeAllObjects];
                            }
                        }
                    } break;
                    case 3: { // 审核失败
                        if (self->currentPageRejected == 1) {
                            if (self->rejectedDataArray.count) {
                                [self->rejectedDataArray removeAllObjects];
                            }
                        }
                    } break;
                    case 4: { // 已隐藏
                        if (self->currentPageHidden == 1) {
                            if (self->hiddenDataArray.count) {
                                [self->hiddenDataArray removeAllObjects];
                            }
                        }
                    } break;
                    default:
                        break;
                }
                for (NSDictionary *dic in data) {
                    CompanyJobModel *model = [[CompanyJobModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    
                    switch (self.selectIndex) {
                        case 0: {
                            [self->allDataArray addObject:model];
                        } break;
                        case 1: {
                            [self->openDataArray addObject:model];
                        } break;
                        case 2: {
                            [self->inreviewDataArray addObject:model];
                        } break;
                        case 3: {
                            [self->rejectedDataArray addObject:model];
                        } break;
                        case 4: {
                            [self->hiddenDataArray addObject:model];
                        } break;
                        default:
                            break;
                    }
                }
                self.noDataView.hidden = YES;
                [self.jobTableView.mj_footer endRefreshing];
                [self.jobTableView reloadData];
            }
            switch (self.selectIndex) {
                case 0: {
                    if (self->allDataArray.count) {
                    } else {
                        self.noDataView.hidden = NO;
                        [self.noDataView vcNilStatusType:VCNilStatusTypeOfCommonNoData superView:self.view];
                    }
                } break;
                case 1: {
                    if (self->openDataArray.count) {
                    } else {
                        self.noDataView.hidden = NO;
                        [self.noDataView vcNilStatusType:VCNilStatusTypeOfCommonNoData superView:self.view];
                    }
                } break;
                case 2: {
                    if (self->inreviewDataArray.count) {
                    } else {
                        self.noDataView.hidden = NO;
                        [self.noDataView vcNilStatusType:VCNilStatusTypeOfCommonNoData superView:self.view];
                    }
                } break;
                case 3: {
                    if (self->rejectedDataArray.count) {
                    } else {
                        self.noDataView.hidden = NO;
                        [self.noDataView vcNilStatusType:VCNilStatusTypeOfCommonNoData superView:self.view];
                    }
                } break;
                case 4: {
                    if (self->hiddenDataArray.count) {
                    } else {
                        self.noDataView.hidden = NO;
                        [self.noDataView vcNilStatusType:VCNilStatusTypeOfCommonNoData superView:self.view];
                    }
                } break;
                default:
                    break;
            }
            SVPHUDDismiss;
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError * _Nonnull error) {
        SVPHUDError(NetErrorAlertText);
        [self.noDataView vcNilStatusType:VCNilStatusTypeOfNoNet superView:self.view];
    }];
}
- (void)initUI {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadDataAndToTop) name:NotificationForCompanyJobRefresh object:nil];
    NSArray *titleArray = @[@"全部", @"开放中", @"审核中", @"审核失败", @"已隐藏"];
    titleView = [[LYTitleView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40*Scale) titlesArray:titleArray norCorlor:THEMECOLOR_OF_TEXT_666666 selectColor:THEMECOLOR_OF_ORANGE];
    __weak typeof(self)weakSelf = self;
    titleView.block = ^(NSInteger index){
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"%li",index);
        strongSelf.selectIndex = index;
        switch (index) {
            case 0: {
                if (self->allDataArray && self->allDataArray.count) {
                    strongSelf.noDataView.hidden = YES;
                    [strongSelf.jobTableView reloadData];
                } else {
                    [strongSelf loadData];
                }
            } break;
            case 1: {
                if (self->openDataArray && self->openDataArray.count) {
                    strongSelf.noDataView.hidden = YES;
                    [strongSelf.jobTableView reloadData];
                } else {
                    [strongSelf loadData];
                }
            } break;
            case 2: {
                if (self->inreviewDataArray && self->inreviewDataArray.count) {
                    strongSelf.noDataView.hidden = YES;
                    [strongSelf.jobTableView reloadData];
                } else {
                    [strongSelf loadData];
                }
            } break;
            case 3: {
                if (self->rejectedDataArray && self->rejectedDataArray.count) {
                    strongSelf.noDataView.hidden = YES;
                    [strongSelf.jobTableView reloadData];
                } else {
                    [strongSelf loadData];
                }
            } break;
            case 4: {
                if (self->hiddenDataArray && self->hiddenDataArray.count) {
                    strongSelf.noDataView.hidden = YES;
                    [strongSelf.jobTableView reloadData];
                } else {
                    [strongSelf loadData];
                }
            } break;
            default:
                break;
        }
    };
    [self.view addSubview:titleView];
    
    self.jobTableView = [UIToolsControl initTableViewWithFrame:CGRectMake(0, EndY(titleView), WIDTH, HEIGHT-HeightOfStatusBarAndNavigationBar-HeightOfTabBar-ViewHeight(titleView)-65*Scale) target:self style:UITableViewStylePlain];
    self.jobTableView.rowHeight = CompanyOfJobStatusCellHeight;
    self.jobTableView.tableFooterView = [[UIView alloc] init];
    self.jobTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.jobTableView];
    
    self.jobTableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        switch (self.selectIndex) {
            case 0: {
                self->currentPageAll++;
            } break;
            case 1: {
                self->currentPageOpen++;
            } break;
            case 2: {
                self->currentPageInreview++;
            } break;
            case 3: {
                self->currentPageRejected++;
            } break;
            case 4: {
                self->currentPageHidden++;
            } break;
            default:
                break;
        }
        [weakSelf.jobTableView.mj_footer beginRefreshing];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf loadData];
        });
    }];
    
    UIButton *jobPostedBtn = [UIToolsControl initButtonWithFrame:CGRectMake(100*Scale, HEIGHT-HeightOfTabBar-HeightOfStatusBarAndNavigationBar-55*Scale, (WIDTH-200*Scale), 46*Scale) imageName:nil target:self action:@selector(jobPostedBtnTap) title:@"发布职位" titleColor:COLOR_OF_WHITE];
    jobPostedBtn.layer.cornerRadius = 23*Scale;
    jobPostedBtn.layer.masksToBounds = YES;
    jobPostedBtn.backgroundColor = THEMECOLOR_OF_ORANGE;
    jobPostedBtn.titleLabel.font = Font(Font_17);
    [self.view addSubview:jobPostedBtn];
}
- (void)jobPostedBtnTap {
    CompanyJobPostedViewController *CJPVC = [[CompanyJobPostedViewController alloc] init];
    CJPVC.hidesBottomBarWhenPushed = YES;
    __weak __typeof(self)weakSelf = self;
    CJPVC.add = ^(BOOL addFlag) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        self->currentPageAll = 1;
        if (self->allDataArray.count) {
            [self->allDataArray removeAllObjects];
        }
        [strongSelf loadData];
    };
    [self.navigationController pushViewController:CJPVC animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (self.selectIndex) {
        case 0: { // 全部
            if (allDataArray.count) {
                return allDataArray.count;
            }
        } break;
        case 1: { // 开放中
            if (openDataArray.count) {
                return openDataArray.count;
            }
        } break;
        case 2: { // 审核中
            if (inreviewDataArray.count) {
                return inreviewDataArray.count;
            }
        } break;
        case 3: { // 审核失败
            if (rejectedDataArray.count) {
                return rejectedDataArray.count;
            }
        } break;
        case 4: { // 已隐藏
            if (hiddenDataArray.count) {
                return hiddenDataArray.count;
            }
        } break;
        default:
            break;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CompanyOfJobStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:isCellID];
    if (!cell) {
        cell = [[CompanyOfJobStatusCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:isCellID];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
//    [cell reloadData];
    switch (self.selectIndex) {
        case 0: { // 全部
            if (allDataArray.count) {
                CompanyJobModel *model = allDataArray[indexPath.row];
                [cell reloadDataModel:model];
            }
        } break;
        case 1: { // 开放中
            if (openDataArray.count) {
                CompanyJobModel *model = openDataArray[indexPath.row];
                [cell reloadDataModel:model];
            }
        } break;
        case 2: { // 审核中
            if (inreviewDataArray.count) {
                CompanyJobModel *model = inreviewDataArray[indexPath.row];
                [cell reloadDataModel:model];
            }
        } break;
        case 3: { // 审核失败
            if (rejectedDataArray.count) {
                CompanyJobModel *model = rejectedDataArray[indexPath.row];
                [cell reloadDataModel:model];
            }
        } break;
        case 4: { // 已隐藏
            if (hiddenDataArray.count) {
                CompanyJobModel *model = hiddenDataArray[indexPath.row];
                [cell reloadDataModel:model];
            }
        } break;
        default:
            break;
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CompanyJobModel *model = [[CompanyJobModel alloc] init];
    CompanyJobDetailViewController *JDVC = [[CompanyJobDetailViewController alloc] init];
    switch (self.selectIndex) {
        case 0: {
            model = allDataArray[indexPath.row];
        } break;
        case 1: {
            model = openDataArray[indexPath.row];
        } break;
        case 2: {
            model = inreviewDataArray[indexPath.row];
        } break;
        case 3: {
            model = rejectedDataArray[indexPath.row];
        } break;
        case 4: {
            model = hiddenDataArray[indexPath.row];
        } break;
        default:
            break;
    }
    JDVC.id = model.id;
    JDVC.showToolButton = YES;
    __weak __typeof(self)weakSelf = self;
    JDVC.edit = ^(BOOL editFlag) {
        if (editFlag) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            self->currentPageAll = 1;
            if (self->allDataArray.count) {
                [self->allDataArray removeAllObjects];
            }
            [strongSelf loadData];
        }
    };
    JDVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:JDVC animated:YES];
}

@end
